/**
 * 拦截器
 */
import type { Method } from 'alova'
import { Notify } from 'quasar'

const showFailNotify = (msg: string) => {
  Notify.create({
    message: msg,
    position: 'top',
    type: 'negative',
  })
}

// const showSuccessNotify = (msg: string) => {
//   Notify.create({
//     message: msg,
//     position: 'top',
//     type: 'success',
//     timeout: 300,
//   })
// }

/**
 * 请求拦截器
 * 添加token/role等
 */

export function beforeRequest(method: Method) {
  // 添加token
  method.config.headers.token = 'token8888'
  method.config.headers.yang = '9999'
}

/**
 * 响应拦截器
 */

export async function onSuccess<T = any>(response: Response) {
  const { status } = response
  /* ——————1. 网络错误—————— */
  if (!status) {
    showFailNotify('网络错误或请求超时')
    throw new Error('网络错误或请求超时')
  }

  // 后端返回的数据结构{ code: 200, data: {...}, msg: 'OK' }

  const responseData: {
    code: number
    data: T
    msg?: string
  } = await response.json()
  /* ——————2. HTTP 状态码错误—————— */
  if (status >= 400) {
    let errorMsg = `请求错误，状态码：${status}`

    switch (status) {
      case 401:
        errorMsg = responseData.msg || '未授权，请重新登录'
        // 跳转至登录页...
        break
      case 403:
        errorMsg = responseData.msg || '拒绝访问'
        break
      case 404:
        errorMsg = responseData.msg || '请求资源不存在'
        break
      case 500:
        errorMsg = responseData.msg || '服务器内部错误'
        break
      default:
        errorMsg = responseData.msg || `请求错误，状态吗：${status}`
    }
    showFailNotify(errorMsg)
    // 抛出错误，以便在具体请求中捕获处理
    throw new Error(errorMsg)
  }

  /* ——————3. 业务错误—————— */
  if (responseData.code !== 200) {
    const errorMsg = responseData.msg || '业务逻辑错误'
    showFailNotify(errorMsg)
    throw new Error(errorMsg)
  }

  /* ——————4. 正确的响应—————— */
  return responseData.data
}

/**
 * 网络异常/代码异常
 */
export function onError(err: Error) {
  showFailNotify(err.message)
}
